package com.example.orderfood2;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.widget.Toolbar;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.example.orderfood2.DatabaseManager.DatabaseManager;
import com.example.orderfood2.Repository.SchoolNewRepository;
import com.example.orderfood2.Repository.StudentAvatarRepository;
import com.example.orderfood2.Repository.StudentRepository;
import com.example.orderfood2.Repository.TimeTableRepository;
import com.example.orderfood2.entity.SchoolNew;
import com.example.orderfood2.entity.TimeTable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class StudentActivity extends AppCompatActivity {
    private FloatingActionButton floatingActionButton;
    private boolean isDragging = false;
    private String account;
    private String date;
    private float lastTouchX, lastTouchY;
    //    DBUtil dbUtil;
    private StudentRepository dbUtil;
    private SchoolNewRepository schoolNewRepository;
    //    创建5个TextView课表
    TextView firstClass, secondClass, thirdClass, fourthClass, fifthClass;
    //    创建5个校园新闻TextView
    TextView theFirst, theSecond, theThird, theFourth, theFifth;
    //    学生id
    private Integer studentId;
    // 1. 声明FloatingActionButton变量
    private FloatingActionButton floatingButton;

    /**
     * ActivityResultLauncher用于启动拍照意图并处理返回结果
     * 该启动器专门用于处理拍照操作的Activity结果回调
     */
    private ActivityResultLauncher<Intent> takePictureLauncher;

    /**
     * ActivityResultLauncher实例，用于请求权限
     * <p>
     * 该成员变量是一个ActivityResultLauncher对象，专门用于启动权限请求操作。
     * 通过registerForActivityResult方法注册，传入权限请求的contract和回调处理逻辑，
     * 实现权限请求结果的异步处理。
     */

    private ActivityResultLauncher<String> requestPermissionLauncher;

    //    学生头像数据库对象
    private StudentAvatarRepository studentAvatarRepository;

    //    学生头像
    private ImageView imageView;
    //    头像存储位置
    private String currentPhotoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 注册 takePictureLauncher - 处理拍照结果
// 修改拍照后的处理逻辑，添加方向校正
        takePictureLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && currentPhotoPath != null) {
                        imageView.setImageURI(Uri.parse(currentPhotoPath));

                        new Thread(() -> {
                            try {
                                // 1. 读取图片旋转角度（关键：使用图片路径）
                                int rotationAngle = studentAvatarRepository.getBitmapRotationAngle(currentPhotoPath);

                                // 2. 解码原始图片
                                Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);
                                if (bitmap == null) {
                                    runOnUiThread(() ->
                                            Toast.makeText(StudentActivity.this, "图片加载失败", Toast.LENGTH_SHORT).show()
                                    );
                                    return;
                                }

                                // 3. 校正方向（如果需要）
                                if (rotationAngle != 0) {
                                    Matrix matrix = new Matrix();
                                    matrix.postRotate(rotationAngle);
                                    Bitmap rotatedBitmap = Bitmap.createBitmap(
                                            bitmap, 0, 0,
                                            bitmap.getWidth(), bitmap.getHeight(),
                                            matrix, true
                                    );
                                    bitmap.recycle(); // 回收原始Bitmap
                                    bitmap = rotatedBitmap;
                                }

                                // 4. 压缩并保存到数据库
                                byte[] imageBytes = StudentAvatarRepository.bitmapToByteArray(bitmap);
                                studentAvatarRepository.uploadAvatar(studentId, imageBytes);

                                runOnUiThread(() ->
                                        Toast.makeText(StudentActivity.this, "头像保存成功", Toast.LENGTH_SHORT).show()
                                );
                                bitmap.recycle();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }).start();
                    }
                }
        );
        // 2. 注册权限请求Launcher
        requestPermissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        // 权限已授予，可以拍照
                        launchCamera();
                    } else {
                        // 权限被拒绝
                        Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show();
                    }
                });

        studentAvatarRepository = DatabaseManager.getInstance(this).getStudentAvatarRepository();
        schoolNewRepository = DatabaseManager.getInstance(this).getSchoolNewRepository();
        dbUtil = DatabaseManager.getInstance(this).getStudentRepository();
        TimeTableRepository timeTableRepository = DatabaseManager.getInstance(this).getTimeTableRepository();
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_student);

//        dbUtil=new DBUtil(this);
        floatingActionButton = findViewById(R.id.floating_button);
        account = getIntent().getStringExtra("account");
        date = dbUtil.getStudentDate(account);
        studentId = dbUtil.getStudentIdByName(account);
        TextView username = findViewById(R.id.manage_name);
        imageView = findViewById(R.id.manage_loge);
//        加载头像
        showAvatar(studentId);
        username.setText(account);
        //字符串切割
        String[] dates = date.split("-");
        //获取系统当前日期
        LocalDate today = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            today = LocalDate.now();
        }
        int month = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            month = today.getMonthValue();
        }
        int day = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            day = today.getDayOfMonth();
        }
//        Toast.makeText(StudentActivity.this,
//                "当前日期: " + month + "月" + day + "日",
//                Toast.LENGTH_SHORT).show();
        //判断是否生日
        if (dates.length >= 3) {
            int storedMonth = Integer.parseInt(dates[1]); // 月份
            int storedDay = Integer.parseInt(dates[2]);   // 日
            if (month == storedMonth && day == storedDay) {
                floatingActionButton.setVisibility(View.VISIBLE);
                floatingActionButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(StudentActivity.this);
                        builder.setTitle("生日快乐！🎂");
                        builder.setMessage("愿你生辰欢悦，学业璀璨，未来皆坦途！");
                        builder.setPositiveButton("谢谢", (dialog, which) -> dialog.dismiss());
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                });
            }
        }

        //给左上图标添加点击事件，并完成左侧边栏弹出
        LinearLayout leftSidebar = findViewById(R.id.Left_sidebar);
        View overlay = findViewById(R.id.overlay);
        Toolbar toolbar = findViewById(R.id.toolbar);
        //        用数组传值
        final int[] targetWidth = {0};
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取参数对象
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) leftSidebar.getLayoutParams();
                // 检查当前宽度，如果是0dp就改为300dp，否则改回0dp（实现点击切换）
                if (params.width == 0) {
                    // 将300dp转换为像素
//                    getResources()用于访问屏幕信息，getDisplayMetrics() 返回 DisplayMetrics 对象，包含当前设备的屏幕信息density：1dp 对应的像素值（px）
                    targetWidth[0] = (int) (300 * getResources().getDisplayMetrics().density);
                    // 创建一个ValueAnimator，从0过渡到目标宽度,即给修改params.width添加动画，就是params.width缓慢从0到300，ValueAnimator 可以在指定的时间内，从一个值平滑地过渡到另一个值
                    ValueAnimator animator = ValueAnimator.ofInt(0, targetWidth[0]);
                    animator.setDuration(300); // 动画持续时间，单位为毫秒
//                    setInterpolator(new LinearInterpolator())：设置插值器为 LinearInterpolator，使动画匀速进行
                    animator.setInterpolator(new LinearInterpolator()); // 设置插值器，使动画匀速进行
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            // 获取当前动画的值
                            int value = (int) animation.getAnimatedValue();
                            // 更新布局参数的宽度
                            params.width = value;
                            leftSidebar.setLayoutParams(params);
                        }
                    });
                    animator.start(); // 启动动画
                    overlay.setVisibility(View.VISIBLE);//将隐藏改为可以操作
                }
            }
        });
        //添加点击事件，当用户触摸大于300的位置时，leftSidebar 由300到0
        overlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取参数对象
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) leftSidebar.getLayoutParams();
                if (params.width > 0) {
                    // 创建一个ValueAnimator，从当前宽度过渡到0
                    ValueAnimator animator = ValueAnimator.ofInt(params.width, 0);
                    animator.setDuration(300); // 动画持续时间，单位为毫秒
                    animator.setInterpolator(new LinearInterpolator()); // 设置插值器，使动画匀速进行
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            // 获取当前动画的值
                            int value = (int) animation.getAnimatedValue();
                            // 更新布局参数的宽度
                            params.width = value;
                            leftSidebar.setLayoutParams(params);
                        }
                    });
                    animator.start(); // 启动动画
                    overlay.setVisibility(View.GONE);//将可以操作改为隐藏
                }
            }
        });
        //退出按钮
        Button student_to_login = findViewById(R.id.student_to_login);
        student_to_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(StudentActivity.this, MainActivity.class);
                // 设置标志以清除任务栈（关键修改）
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(i);
                // 结束当前Activity（确保退出）
                finish();
            }
        });
        //修改密码
        Button student_change_password = findViewById(R.id.student_change_password);
        student_change_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PasswordChangeDialogStudent.showPasswordChangeDialogStudent(StudentActivity.this, account);
            }
        });


//        展示课表
        //        分别给5个TextView绑定元素
        firstClass = findViewById(R.id.first_class);
        secondClass = findViewById(R.id.second_class);
        thirdClass = findViewById(R.id.third_class);
        fourthClass = findViewById(R.id.fourth_class);
        fifthClass = findViewById(R.id.fifth_class);
        TimeTable timeTables = timeTableRepository.queryTimeTableByStudentId(studentId);
//        分别给5个TextView绑定课程
        if (timeTables != null) {
            firstClass.setText(timeTables.getFirstClass());
            secondClass.setText(timeTables.getSecondClass());
            thirdClass.setText(timeTables.getThirdClass());
            fourthClass.setText(timeTables.getFourthClass());
            fifthClass.setText(timeTables.getFifthClass());
        }
//        调用函数显示课表
        showTimeTable();
//        调用函数给floatingButton添加点击事件
        setLatestSchoolNew();

//// 上传头像按钮
        Button studentUploadAvatar = findViewById(R.id.student_upload_avatar);
        studentUploadAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePicture();
            }
        });

    }

    private void showAvatar(Integer studentId) {
        byte[] avatarByStudentId = studentAvatarRepository.getAvatarByStudentId(studentId);
        Bitmap bitmap = studentAvatarRepository.byteArrayToBitmap(avatarByStudentId);
//      将bitmap赋值给imageView
        imageView.setImageBitmap(bitmap);
    }

    private void takePicture() {

        // 检查相机权限
//        这段代码用于检查应用是否已获得相机权限。checkSelfPermission方法会检测CAMERA权限是否已被授予，如果返回值等于PackageManager.PERMISSION_GRANTED，表示权限已获取。
        if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            // 已经有权限，直接启动相机
            launchCamera();
        } else {
//            请求权限
            requestPermissionLauncher.launch(Manifest.permission.CAMERA);
        }
    }

    private void launchCamera() {
//        准备相机页面
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 确保有相机应用可以处理这个意图
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (Exception ex) {
                ex.printStackTrace();
                Toast.makeText(this, "创建文件失败", Toast.LENGTH_SHORT).show();
                return;
            }
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.orderfood2.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                takePictureLauncher.launch(takePictureIntent);
            }
        } else {
            Toast.makeText(this, "没有找到相机应用", Toast.LENGTH_SHORT).show();

        }
    }

    private File createImageFile() throws IOException {
        // 创建唯一的文件名
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        // 存储在应用的私有目录中
        File storageDir = getExternalFilesDir(null);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        // 保存文件路径用于后续使用
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }


    private void setLatestSchoolNew() {
        // 2. 在Activity的onCreate方法中初始化
        floatingButton = findViewById(R.id.floating_button);
        floatingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取最新新闻
                SchoolNew latestSchoolNew = schoolNewRepository.queryLatestSchoolNew();
                if (latestSchoolNew != null) {
//                    使用弹窗展示标题和内容
                    AlertDialog.Builder builder = new AlertDialog.Builder(StudentActivity.this);
                    builder.setTitle(latestSchoolNew.getTitle());
                    builder.setMessage(latestSchoolNew.getContent());
                    builder.setPositiveButton("确定", null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                } else {
                    Toast.makeText(StudentActivity.this, "暂无最新新闻", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void showTimeTable() {
        List<SchoolNew> schoolNews = schoolNewRepository.querySchoolNews();
        theFirst = findViewById(R.id.the_first);
        theSecond = findViewById(R.id.the_second);
        theThird = findViewById(R.id.the_third);
        theFourth = findViewById(R.id.the_fourth);
        theFifth = findViewById(R.id.the_fifth);

        // 设置文本 - 注意：这里应该根据数据索引来设置不同的新闻
        if (schoolNews != null && !schoolNews.isEmpty()) {
            // 设置第一条新闻
            if (schoolNews.size() > 0) {
                theFirst.setText(schoolNews.get(0).getTitle());
            }
            // 设置第二条新闻
            if (schoolNews.size() > 1) {
                theSecond.setText(schoolNews.get(1).getTitle());
            }
            // 设置第三条新闻
            if (schoolNews.size() > 2) {
                theThird.setText(schoolNews.get(2).getTitle());
            }
            // 设置第四条新闻
            if (schoolNews.size() > 3) {
                theFourth.setText(schoolNews.get(3).getTitle());
            }
            // 设置第五条新闻
            if (schoolNews.size() > 4) {
                theFifth.setText(schoolNews.get(4).getTitle());
            }
        }
//        给每个TextView添加点击事件，使用弹窗展示标题和内容
        if (schoolNews != null && !schoolNews.isEmpty()) {
            theFirst.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 创建一个弹窗
                    AlertDialog.Builder builder = new AlertDialog.Builder(StudentActivity.this);
                    builder.setTitle(schoolNews.get(0).getTitle());
                    builder.setMessage(schoolNews.get(0).getContent());
                    builder.setPositiveButton("确定", null);
                    builder.show();
                }
            });
        }
        if (schoolNews.size() > 1) {
            theSecond.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 创建一个弹窗
                    AlertDialog.Builder builder = new AlertDialog.Builder(StudentActivity.this);
                    builder.setTitle(schoolNews.get(1).getTitle());
                    builder.setMessage(schoolNews.get(1).getContent());
                    builder.setPositiveButton("确定", null);
                    builder.show();
                }
            });
        }
        if (schoolNews.size() > 2) {
            theThird.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 创建一个弹窗
                    AlertDialog.Builder builder = new AlertDialog.Builder(StudentActivity.this);
                    builder.setTitle(schoolNews.get(2).getTitle());
                    builder.setMessage(schoolNews.get(2).getContent());
                    builder.setPositiveButton("确定", null);
                    builder.show();
                }
            });
        }
        if (schoolNews.size() > 3) {
            theThird.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 创建一个弹窗
                    AlertDialog.Builder builder = new AlertDialog.Builder(StudentActivity.this);
                    builder.setTitle(schoolNews.get(3).getTitle());
                    builder.setMessage(schoolNews.get(3).getContent());
                    builder.setPositiveButton("确定", null);
                }
            });
        }
        if (schoolNews.size() > 4) {
            theFourth.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 创建一个弹窗
                    AlertDialog.Builder builder = new AlertDialog.Builder(StudentActivity.this);
                    builder.setTitle(schoolNews.get(3).getTitle());
                    builder.setMessage(schoolNews.get(3).getContent());
                    builder.setPositiveButton("确定", null);
                    builder.show();
                }
            });
        }
        if (schoolNews.size() > 5) {
            theFifth.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(StudentActivity.this);
                    builder.setTitle(schoolNews.get(4).getTitle());
                    builder.setMessage(schoolNews.get(4).getContent());
                    builder.setPositiveButton("确定", null);
                    builder.show();
                }
            });
        }

    }




}
